
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <cedule/log.h>

#include "config.h"

char * default_users[] = {
	"bob",
	"max",
	"jules",
	"ali",
	"julie",
	"lea",
	"momo",
	"ines",
	NULL
};


/**
 * create a config object filled with default values
 */
Config_t * config_create() {
	Config_t * result;

	result = (Config_t*) malloc( sizeof( Config_t ) );
	if ( ! result ) goto error;

	result->port = 1100; /* default port */
	result->users = default_users;
	result->verbose = 0; /* quiet by default */
	result->detach = 1; /* background by default */

	return result;

error:
	return NULL;
}

static void config_usage( const char * exec_name )
{
	printf("Usage: %s [options]\n", exec_name);
	/*	printf("  -c <file>       use given configuration file\n");  */
	printf("  -f              stay in foreground (disabled by default)\n"); 
	printf("  -v              verbose mode (disabled by default)\n");
	printf("  -h              this help\n"); 
}


/**
 * destroy config object and free memory
 */
void config_destroy( Config_t * config ) 
{
	if ( config )
		free( config );
}


/**
 * check that all parameters are coherent 
 */
int config_is_valid( Config_t * config ) 
{
	/* FIXME: should really validate config parameters instead of sending fake values */
	return 1;
}

int config_parse_cmdline( Config_t* conf, int argc, char** argv) 
{
	int opt;

	if ( !conf )
		return -1;

	//while ((opt = getopt(argc, argv, "c:hfv")) != -1) {
	while ((opt = getopt(argc, argv, "hfv")) != -1) {
		switch(opt) {
			/*
			case 'c':
				if (optarg)
					conf->config_file = strdup( optarg );
				else
					config_usage( argv[0] );
				break;
			*/
			case 'h':
				config_usage( argv[0] );
				break;

			case 'f':
				conf->detach = 0;
				log_daemonized = 0;
				break;

			case 'v':
				conf->verbose = 1;
				log_verbosity = 1;
				break;

			default:
				log_error( "Bad argument %c\n", opt );
		}
	}

	return 0;
}
